package com.example.venue_reservation_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.venue_reservation_service.domain.School;
import com.example.venue_reservation_service.domain.User;
import com.example.venue_reservation_service.entity.PersonInfo;
import com.example.venue_reservation_service.entity.ResponseData;
import com.example.venue_reservation_service.exception.IdentityApiException;
import com.example.venue_reservation_service.mapper.InstitutionMapper;
import com.example.venue_reservation_service.mapper.UserMapper;
import com.example.venue_reservation_service.service.SchoolService;
import com.example.venue_reservation_service.mapper.SchoolMapper;
import com.example.venue_reservation_service.utils.IdentityUtil;
import com.example.venue_reservation_service.vo.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
* @author 31586
* @description 针对表【venue_school(学校身份表)】的数据库操作Service实现
* @createDate 2025-01-05 15:42:15
*/
@Service
@Slf4j
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School>
    implements SchoolService{

    @Resource
    private InstitutionMapper institutionMapper;

    @Resource
    private UserMapper userMapper;

    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public Result queryUnits(String type) {
        return Result.
                ok(institutionMapper.selectByType("学生".equalsIgnoreCase(type) ? "学院与教学机构" : null)).
                message("数据获取成功");
    }

    @Override
    public Result userCertify(School school) {

        User user = userMapper.selectById(school.getUserId());
        if (Optional.ofNullable(user).isEmpty()) {
            return Result.fail().message("用户信息不存在");
        }
//        if(user.getIsCertify() == 1 && user.getOperableTimes() == 2){
//            return Result.fail().message("修改次数已用完，请联系管理员");
//        }
        // 获取认证类型（教职工 or 学生）
        if(!"学生".equals(school.getType())){
            // 调用学校身份认证接口
            PersonInfo info;
            try {
                String result = IdentityUtil.getGzzxList(school.getDescription());
                ResponseData data = mapper.readValue(result, ResponseData.class);
                if(data.getMessage().size() == 0){
                    return Result.fail().message("未查询到教职工信息");
                }
                info = data.getMessage().get(0);
            } catch (Exception e) {
                throw new IdentityApiException("身份认证服务暂时不可用，请稍后再试");
            }
            if(!school.getSchoolNumber().equals(info.getEmployeeId())){
                return Result.fail().message("工号与联系方式不匹配");
            }
        }
        School one = getOne(Wrappers.<School>lambdaQuery().eq(School::getUserId, school.getUserId()));
        if(Optional.ofNullable(one).isEmpty()){
            one = new School();
        }
        BeanUtil.copyProperties(school, one, "id");
        saveOrUpdate(one);
        user.setOperableTimes(user.getIsCertify() == 1 ? Math.max(user.getOperableTimes() - 1, 0) : 2);
        user.setIsCertify(1);
        userMapper.updateById(user);
        return Result.ok(one).message("身份认证成功");
    }

    @Override
    public Result getCertify(Integer userId) {
        User user = userMapper.selectById(userId);
        if (Optional.ofNullable(user).isEmpty()) {
            return Result.fail().message("用户信息不存在");
        }
        if (user.getIsCertify() == 0) {
            return Result.ok().message("用户未认证");
        }
        return Result.ok(getOne(Wrappers.<School>lambdaQuery().eq(School::getUserId, userId))).message("查询成功");
    }

}




